package com.atguigu.tingshu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.order.util.DelayMesageUtil;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    /**
     * 获取订单确认页面所需数据
     * - 购买VIP套餐
     * - 购买专辑
     * - 购买声音
     *
     * @param tradeVo {itemType:"项目类型",:itemId:"项目",trackCount:"声音数量"}
     * @return 订单vo对象->为后续提交订单准备
     */
    @Override
    public OrderInfoVo getOrderTradeData(TradeVo tradeVo) {
        Long userId = AuthContextHolder.getUserId();
        //1.创建订单信息VO对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();

        //1.1 声明默认价格 TODO：一定要传入字符串必须是 "0.00"
        //1.1.1 "商品"原价
        BigDecimal originalAmount = new BigDecimal("0.00");
        //1.1.2 "商品"减免价
        BigDecimal derateAmount = new BigDecimal("0.00");
        //1.1.3 "商品"订单价
        BigDecimal orderAmount = new BigDecimal("0.00");

        //1.2 声明商品列表集合
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();

        //1.3 声明优惠列表集合
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //2.处理VIP会员（允许重复） 1001-专辑 1002-声音 1003-vip会员
        if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(tradeVo.getItemType())) {
            //2.1 根据选择套餐ID远程调用“用户服务”获取套餐信息(商品信息)
            VipServiceConfig vipServiceConfig = userFeignClient.getVipServiceConfig(tradeVo.getItemId()).getData();
            Assert.notNull(vipServiceConfig, "套餐{}信息为空", tradeVo.getItemId());

            //2.2 为订单VO中商品价格赋值-原价、减免价、订单价
            originalAmount = vipServiceConfig.getPrice();
            orderAmount = vipServiceConfig.getDiscountPrice();
            derateAmount = originalAmount.subtract(orderAmount);

            //2.3 封装商品明细列表
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName("套餐：" + vipServiceConfig.getName());
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            //商品信息中价格为：原价
            orderDetailVo.setItemPrice(originalAmount);
            orderDetailVoList.add(orderDetailVo);

            //2.4 封装商品优惠明细列表
            if (originalAmount.compareTo(orderAmount) != 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("VIP套餐限时优惠：{}" + derateAmount);
                orderDerateVoList.add(orderDerateVo);
            }
        } else if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(tradeVo.getItemType())) {
            //3. 处理专辑（不允许重复购买）
            //3.1 远程调用"用户服务"-判断用户是否已购专辑
            Boolean isPaid = userFeignClient.isPaidAlbum(tradeVo.getItemId()).getData();
            if (isPaid) {
                throw new GuiguException(ResultCodeEnum.REPEAT_BUY_ERROR);
            }
            //3.2 远程调用"用户服务"-获取当前用户身份信息
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
            Assert.notNull(userInfoVo, "用户{}不存在", userId);
            int isVip = userInfoVo.getIsVip().intValue();
            //3.3 远程调用"专辑服务"-获取专辑信息-得到价格及不同用户折扣
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(tradeVo.getItemId()).getData();
            Assert.notNull(albumInfo, "专辑{}不存在", tradeVo.getItemId());
            //3.4 计算专辑价格封装原价，订单价，减免价   订单价=原价*折扣
            originalAmount = albumInfo.getPrice();
            orderAmount = originalAmount;
            //3.4.1 判断当前专辑是否有普通用户折扣（是否不等于-1） 且 当前用户是普通用户/VIP过期
            if (albumInfo.getDiscount().intValue() != -1) {
                if (isVip == 0 || (isVip == 1 && new Date().after(userInfoVo.getVipExpireTime()))) {
                    //3.4.2 计算普通用户享受折扣   折扣8代表打8折
                    orderAmount = originalAmount.multiply(albumInfo.getDiscount()).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
            }
            //3.4.3 判断当前专辑是否有VIP用户折扣
            if (albumInfo.getVipDiscount().intValue() != -1) {
                if (isVip == 1 && userInfoVo.getVipExpireTime().after(new Date())) {
                    //3.4.2 计算VIP用户享受折扣   折扣8代表打8折
                    orderAmount = originalAmount.multiply(albumInfo.getVipDiscount()).divide(new BigDecimal("10"), 2, RoundingMode.HALF_UP);
                }
            }
            derateAmount = originalAmount.subtract(orderAmount);
            //3.5 封装商品明细列表
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName("专辑：" + albumInfo.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemPrice(originalAmount);
            orderDetailVoList.add(orderDetailVo);

            //3.6 封装商品优惠列表
            if (derateAmount.compareTo(new BigDecimal("0.00")) != 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("专辑减免：" + derateAmount);
                orderDerateVoList.add(orderDerateVo);
            }
        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(tradeVo.getItemType())) {
            //4.处理声音（不允许重复购买）
            //4.1 远程调用"专辑服务"获取待购买声音列表
            List<TrackInfo> waitBuyTrackInfoList =
                    albumFeignClient.getUserWaitBuyTrackInfoList(tradeVo.getItemId(), tradeVo.getTrackCount()).getData();
            if (CollectionUtil.isEmpty(waitBuyTrackInfoList)) {
                throw new GuiguException(400, "没有符合计算要求声音！");
            }
            //4.2 远程调用"专辑服务"获取专辑信息-得到声音单价
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(waitBuyTrackInfoList.get(0).getAlbumId()).getData();
            //声音单价
            BigDecimal price = albumInfo.getPrice();

            //4.3 计算用户购买声音价格（原价=订单价）
            originalAmount = price.multiply(new BigDecimal(waitBuyTrackInfoList.size()));
            orderAmount = originalAmount;

            //4.4 封装本次订单中商品清单列表
            orderDetailVoList = waitBuyTrackInfoList.stream()
                    .map(trackInfo -> {
                        OrderDetailVo orderDetailVo = new OrderDetailVo();
                        orderDetailVo.setItemId(trackInfo.getId());
                        orderDetailVo.setItemName(trackInfo.getTrackTitle());
                        orderDetailVo.setItemUrl(trackInfo.getCoverUrl());
                        orderDetailVo.setItemPrice(price);
                        return orderDetailVo;
                    }).collect(Collectors.toList());
        }
        //5.订单信息VO中三种商品订单确认 共有属性
        //5.1 封装购买项目类型
        orderInfoVo.setItemType(tradeVo.getItemType());
        //5.2 封装商品相关价格信息及商品清单
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setDerateAmount(derateAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        //5.3 生成订单流水号
        //5.3.1 构建当前用户本次订单流水号Key
        String tradeKey = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //5.3.2 采用全局唯一字符串作为流水号Value
        String tradeNo = IdUtil.randomUUID();
        //5.3.3 将流水号存入Redis
        redisTemplate.opsForValue().set(tradeKey, tradeNo, 5, TimeUnit.MINUTES);
        //5.3.4 封装流水号
        orderInfoVo.setTradeNo(tradeNo);

        //5.4 生成时间戳-确认订单跟提交订单间隔时间太长
        orderInfoVo.setTimestamp(DateUtil.current());
        //5.5 生订单签名
        //5.5.1 将订单VO转为Map TODO:无法确认支付方式 将payWay空属性排除
        Map<String, Object> map = BeanUtil.beanToMap(orderInfoVo, false, true);
        //5.5.2 生成签名
        String sign = SignHelper.getSign(map);
        orderInfoVo.setSign(sign);

        //6.返回订单VO对象
        return orderInfoVo;
    }

    @Autowired
    private AccountFeignClient accountFeignClient;

    @Autowired
    private DelayMesageUtil delayMesageUtil;

    /**
     * 当前用户提交订单（可能包含余额支付）
     *
     * @param orderInfoVo 订单VO信息
     * @return {orderNo:订单唯一编号}
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Map<String, String> submitOrder(OrderInfoVo orderInfoVo) {
        Long userId = AuthContextHolder.getUserId();
        //1.业务校验，验证流水号-避免用户误操作回退页面导致订单重复提交
        //1.1 构建当前用户存入Redis流水号Key
        String key = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //1.2 采用Lua脚本-判断用户提交流水号跟Redis中是否一致，如果一致删除Redis中流水号
        String scriptText = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "    return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                "    return 0\n" +
                "end";
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(scriptText, Boolean.class);
        //1.3 执行lua脚本
        Boolean flag = (Boolean) redisTemplate.execute(redisScript, Arrays.asList(key), orderInfoVo.getTradeNo());
        if (!flag) {
            throw new GuiguException(400, "流水号异常请重试！");
        }

        //2.业务校验，验证签名-避免用户篡改订单中任意信息 TODO:当时订单确认页面相应签名：没有加入支付方式"payWay"
        //2.1 将订单信息vo转为Map
        Map<String, Object> mapPrams = BeanUtil.beanToMap(orderInfoVo);
        //2.2 将Map参数中payWay排除掉
        mapPrams.remove("payWay");
        //2.3 验证签名-内部逻辑 1.获取原有旧的的签名值 2.将参数中旧签名移除掉，对所有业务数据再次进行签名
        SignHelper.checkSign(mapPrams);

        //3.处理订单相关业务（保存订单及订单明细，订单优惠明细）
        OrderInfo orderInfo = this.saveOrderInfo(orderInfoVo, userId);

        //4.如果用户采用余额支付（声音仅支持余额支付）
        // 订单支付方式 1101-微信 1102-支付宝 1103-账户余额
        if (SystemConstant.ORDER_PAY_ACCOUNT.equals(orderInfoVo.getPayWay())) {
            //4.1 远程调用账户服务进行余额扣减
            //4.1.1 构建扣减余额VO对象
            AccountDeductVo accountDeductVo = new AccountDeductVo();
            accountDeductVo.setOrderNo(orderInfo.getOrderNo());
            accountDeductVo.setUserId(userId);
            accountDeductVo.setAmount(orderInfo.getOrderAmount());
            accountDeductVo.setContent(orderInfo.getOrderTitle());
            //4.1.2 远程调用判断返回结果业务状态码是否200
            Result accountResult = accountFeignClient.checkAndDeduct(accountDeductVo);
            if (!ResultCodeEnum.SUCCESS.getCode().equals(accountResult.getCode())) {
                throw new GuiguException(500, "余额不足，请充值！");
            }
            //4.2 远程调用用户服务进行虚拟物品发货
            //4.2.1 构建购买记录VO对象
            //4.2.2 远程调用判断返回结果业务状态码是否200
            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
            userPaidRecordVo.setOrderNo(orderInfo.getOrderNo());
            userPaidRecordVo.setUserId(userId);
            userPaidRecordVo.setItemType(orderInfoVo.getItemType());
            List<OrderDetailVo> orderDetailVoList = orderInfoVo.getOrderDetailVoList();
            if (CollectionUtil.isNotEmpty(orderDetailVoList)) {
                List<Long> itemIdList =
                        orderDetailVoList.stream()
                                .map(OrderDetailVo::getItemId).collect(Collectors.toList());
                userPaidRecordVo.setItemIdList(itemIdList);
            }

            Result userResult = userFeignClient.savePaidRecord(userPaidRecordVo);
            if (!ResultCodeEnum.SUCCESS.getCode().equals(userResult.getCode())) {
                throw new GuiguException(500, "发货失败，请联系管理员！");
            }

            //4.3 更新订单支付状态：已支付
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
            orderInfoMapper.updateById(orderInfo);

        }

        //6.发送延迟消息，用于验证订单支付状态且关闭订单 测试：1分钟 正式：15分钟
        delayMesageUtil.sendDelayMessage(KafkaConstant.QUEUE_ORDER_CANCEL, orderInfo.getId().toString(), 15, TimeUnit.MINUTES);

        //5.构建Map封装订单编号返回结果
        Map<String, String> map = new HashMap<>();
        map.put("orderNo", orderInfo.getOrderNo());
        return map;
    }

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderDerateMapper orderDerateMapper;

    /**
     * 保存订单包含订单明细跟优惠明细
     *
     * @param orderInfoVo 订单VO信息
     * @param userId      用户ID
     * @return 订单对象
     */
    @Override
    public OrderInfo saveOrderInfo(OrderInfoVo orderInfoVo, Long userId) {
        //1.保存订单信息
        //1.1 将前端提交订单基本属性拷贝对象方式拷贝到订单对象中
        OrderInfo orderInfo = BeanUtil.copyProperties(orderInfoVo, OrderInfo.class);
        //1.2 用户ID
        orderInfo.setUserId(userId);
        //1.3 订单标题 从商品明细VO中获取
        List<OrderDetailVo> orderDetailVoList = orderInfoVo.getOrderDetailVoList();
        String itemName = orderDetailVoList.get(0).getItemName();
        orderInfo.setOrderTitle(itemName);
        //1.4 订单状态：未支付
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_UNPAID);
        //1.5 订单编号 确保订单编号全局唯一 跟后续第三方支付对接使用到 规则：年月日+雪花算法分布式ID
        String today = DateUtil.today().replaceAll("-", "");
        String orderNo = today + IdUtil.getSnowflakeNextId();
        orderInfo.setOrderNo(orderNo);
        orderInfoMapper.insert(orderInfo);
        Long orderId = orderInfo.getId();

        //2.保存订单商品明细
        orderDetailVoList.stream()
                .forEach(orderDetailVo -> {
                    OrderDetail orderDetail = BeanUtil.copyProperties(orderDetailVo, OrderDetail.class);
                    //关联订单ID
                    orderDetail.setOrderId(orderId);
                    //保存订单明细
                    orderDetailMapper.insert(orderDetail);
                });

        //3.保存订单优惠明细
        List<OrderDerateVo> orderDerateVoList = orderInfoVo.getOrderDerateVoList();
        if (CollectionUtil.isNotEmpty(orderDerateVoList)) {
            orderDerateVoList.stream().forEach(orderDerateVo -> {
                OrderDerate orderDerate = BeanUtil.copyProperties(orderDerateVo, OrderDerate.class);
                //关联订单ID
                orderDerate.setOrderId(orderId);
                //保存优惠明细
                orderDerateMapper.insert(orderDerate);
            });
        }
        return orderInfo;
    }

    /**
     * 查询当前用户指定订单信息
     *
     * @param orderNo 订单编号
     * @return 订单信息包含：商品列表，优惠列表
     */
    @Override
    public OrderInfo getOrderInfo(String orderNo) {
        Long userId = AuthContextHolder.getUserId();
        //1.根据订单编号+用户ID查询订单信息
        LambdaQueryWrapper<OrderInfo> orderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderInfoLambdaQueryWrapper.eq(OrderInfo::getUserId, userId);
        orderInfoLambdaQueryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(orderInfoLambdaQueryWrapper);

        if (orderInfo != null) {
            //2.根据订单ID查询订单明细列表
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orderInfo.getId());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
            orderInfo.setOrderDetailList(orderDetailList);


            //3.根据订单ID查询订单优惠列表
            LambdaQueryWrapper<OrderDerate> orderDerateLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDerateLambdaQueryWrapper.eq(OrderDerate::getOrderId, orderInfo.getId());
            List<OrderDerate> orderDerateList = orderDerateMapper.selectList(orderDerateLambdaQueryWrapper);
            orderInfo.setOrderDerateList(orderDerateList);
        }
        return orderInfo;
    }


    /**
     * 查询当前用户订单列表（包含订单商品明细）
     *
     * @param pageInfo 分页对象
     * @return
     */
    @Override
    public void getUserOrderByPage(Page<OrderInfo> pageInfo) {
        Long userId = AuthContextHolder.getUserId();
        //1.获取持久层接口，通过动态SQL查询订单列表
        orderInfoMapper.getUserOrderByPage1(pageInfo, userId);
    }


    /**
     * 根据订单ID查询订单状态，未支付：改为取消
     *
     * @param orderId 订单
     */
    @Override
    public void orderCancel(Long orderId) {
        //1.根据订单ID查询订单信息
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        //2.判断订单状态
        if (orderInfo != null && SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) {
            //3.修改订单状态：已取消
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_CANCEL);
            orderInfoMapper.updateById(orderInfo);
        }
    }

    /**
     * 在线付款成功后-更新订单支付状态（新增购买记录）
     *
     * @param orderNo
     * @return
     */
    @Override
    public void orderPaySuccess(String orderNo) {
        //1.更新订单状态
        //1.1 根据订单编号查询订单 判断状态
        OrderInfo orderInfo = this.getOrderInfoByOrderNo(orderNo);
        if (orderInfo != null) {
            //1.2 更新订单状态：已支付
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
            orderInfoMapper.updateById(orderInfo);
            //2.远程调用用户服务进行虚拟物品发货
            //2.1 构建购买记录VO对象
            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
            userPaidRecordVo.setOrderNo(orderNo);
            userPaidRecordVo.setUserId(orderInfo.getUserId());
            userPaidRecordVo.setItemType(orderInfo.getItemType());
            List<Long> itemIdList = orderInfo.getOrderDetailList()
                    .stream()
                    .map(OrderDetail::getItemId)
                    .collect(Collectors.toList());
            userPaidRecordVo.setItemIdList(itemIdList);

            //2.2 远程调用结果判断业务状态必须200 反之：抛出异常，全局事务回滚
            Result result = userFeignClient.savePaidRecord(userPaidRecordVo);
            if (!ResultCodeEnum.SUCCESS.getCode().equals(result.getCode())) {
                log.error("[订单服务]远程调用用户服务虚拟物品发货异常", result.getMessage());
                throw new GuiguException(400, "购买记录新增异常！");
            }
        }

    }

    @Override
    public OrderInfo getOrderInfoByOrderNo(String orderNo) {
        //1.根据订单编号+用户ID查询订单信息
        LambdaQueryWrapper<OrderInfo> orderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderInfoLambdaQueryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(orderInfoLambdaQueryWrapper);

        if (orderInfo != null) {
            //2.根据订单ID查询订单明细列表
            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orderInfo.getId());
            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
            orderInfo.setOrderDetailList(orderDetailList);


            //3.根据订单ID查询订单优惠列表
            LambdaQueryWrapper<OrderDerate> orderDerateLambdaQueryWrapper = new LambdaQueryWrapper<>();
            orderDerateLambdaQueryWrapper.eq(OrderDerate::getOrderId, orderInfo.getId());
            List<OrderDerate> orderDerateList = orderDerateMapper.selectList(orderDerateLambdaQueryWrapper);
            orderInfo.setOrderDerateList(orderDerateList);
        }
        return orderInfo;
    }


}
